package sistem.management.servlets;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import sistem.manangement.model.UserType;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.labs.repackaged.org.json.JSONArray;
import com.google.appengine.labs.repackaged.org.json.JSONException;
import com.google.appengine.labs.repackaged.org.json.JSONObject;

public class ListaMedici extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
		Query query = new Query("user");
		List<Entity> useri = datastore.prepare(query).asList(FetchOptions.Builder.withDefaults());
		List<Entity> medici = new ArrayList<Entity>();
		if (useri != null) {
			for (Entity user : useri) {
				if (user.getProperty("usertype").equals(UserType.MEDIC.toString())) {
					medici.add(user);
				}
			}
		}
		JSONArray jsonArray = new JSONArray();
		if (medici.size() > 0) {
			for (Entity medic : medici) {
				JSONObject json = new JSONObject();
				String numeMedic = medic.getProperty("nume") + " " + medic.getProperty("prenume");
				try {
					json.put("numeMedic", numeMedic);
					json.put("email", medic.getProperty("email"));
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				jsonArray.put(json);
			}
		}
		System.out.println(jsonArray.toString());
		resp.getWriter().print(jsonArray.toString());
		
	}

}
